package com.pas.connectivitystoreconsumer;

import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class ServiceConsumer {

	private String _url;

	public ServiceConsumer(String url) {
		_url = url;
	}

	public String execute() {
		String result = "";

		try {
			URL text = new URL(_url);
			XmlPullParserFactory parserCreator = XmlPullParserFactory
					.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();

			parser.setInput(text.openStream(), null);

			int parserEvent = parser.getEventType();

			boolean success = false;
			String action = "";
			String errorDescription = "";
			String errorCode = "";

			boolean inFailure = false;

			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				switch (parserEvent) {
				case XmlPullParser.START_TAG:
					if (Utilities.TAG_FAILURE.equals(parser.getName())) {

						action = parser.getAttributeValue(null,
								Utilities.PARAMETER_ACTION);
						errorCode = parser.getAttributeValue(null,
								Utilities.PARAMETER_ERROR_CODE);
						success = false;
						inFailure = true;
					} else if (Utilities.TAG_SUCCESS.equals(parser.getName())) {
						action = parser.getAttributeValue(null,
								Utilities.PARAMETER_ACTION);
						success = true;
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				case XmlPullParser.TEXT:
					if (inFailure) {
						errorDescription = parser.getText();
						inFailure = false;
					}
					break;
				}

				parserEvent = parser.next();
			}

			if (success) {
				result = "Success - Action: " + action;
			} else {
				result = "Failure - Action: " + action;
				result += "\n Error code: " + errorCode + " Description: "
						+ errorDescription;
			}

		} catch (Exception e) {
			result = e.getMessage();
		}

		return result;
	}
}
